/*
 * Copyright (c) 2001-2018 GuaHao.com Corporation Limited. All rights reserved.
 * This software is the confidential and proprietary information of GuaHao Company.
 * ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with GuaHao.com.
 */
package com.bgt.springboot.first.utils;

/**
 * TODO
 *
 * @author Ricky
 * @version V1.0
 * @since 2018-08-08 14:09
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;

/**
 * Created by baiguantao on 2017/6/13.
 * http线程池管理
 */
public class HttpUtils {
    private static PoolingHttpClientConnectionManager clientConnectionManager = null;
    //    private static RequestConfig requestConfig = RequestConfig.DEFAULT;
    private static   RequestConfig requestConfig = null;
    private static boolean logflag=false;

    static {
        LogManager.getRootLogger().setLevel(Level.INFO);
       /* System.setProperty( "log4j.logger.org.springframework","info");
        System.setProperty( "rootLogger.level","info");
        System.setProperty( "log4j.rootLogger","info");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "false");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "info");
        System.setProperty("log4j.logger.org.apache.commons.httpclient", "stdout");
        System.setProperty("log4j.logger.org.apache.http", "stdout");
//        java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(Level.INFO);
//        java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(Level.INFO);
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");*/
    }
    private static HttpClient httpClient = HttpClients.createDefault();
    {
        requestConfig=RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
            .setSocketTimeout(5000).build();
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .build();
        clientConnectionManager=new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        clientConnectionManager.setMaxTotal(50);
        clientConnectionManager.setDefaultMaxPerRoute(25);
        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("sessionID", "######");
        cookie.setDomain("#####");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
        HttpClients.custom().setConnectionManager(clientConnectionManager).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();
    }

    public static String post2(String url, String ext) {

        if(logflag) System.out.println("send request url -> " + url);
        if(logflag)System.out.println("send request params -> " + ext);
        String result = null;
        try {
            result = postSendHttp(url, ext);
        } catch (Exception e) {
            System.out.println("post error"+ e);
        }
        System.out.println("receive response --> " + result);
        return result.toString();
    }
    public static String post3(String url, String ext) {

        if(logflag) System.out.println("send request url -> " + url);
        if(logflag) System.out.println("send request params -> " + ext);
        String result = null;
        try {
            result = postSendHttpAndHeader(url, ext);
        } catch (Exception e) {
            System.out.println("post error"+ e);
        }
        if(logflag)System.out.println("receive response --> " + result);
        return result.toString();
    }
    /**
     * 发送post请求
     * @param url
     * @param body
     * @return
     */
    private static String postSendHttp(String url, String body) {
        if(logflag) System.out.println("请求[参数] - " + body);
        long start = System.currentTimeMillis();
        if (url == null || "".equals(url)) {
            if(logflag) System.out.println("request url is empty.");
            return null;
        }
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        String resultString = null;
        try {
            StringEntity stringEntity = new StringEntity(body, "UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
            // 设置请求主体
            post.setEntity(stringEntity);
            // 发起交易
            HttpResponse resp = httpClient.execute(post);
            int ret = resp.getStatusLine().getStatusCode();
            if (ret == HttpStatus.SC_OK) {
                // 响应分析
                HttpEntity entity = resp.getEntity();

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuffer responseString = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                    responseString.append(result);
                    result = br.readLine();
                }
                long end = System.currentTimeMillis();
                if(logflag) System.out.println("请求[" + url + "]消耗时间 " + (end - start) + "毫秒");
                resultString = responseString.toString();
                if(logflag)System.out.println("响应内容 - " + resultString);
            } else {
                if(logflag)  System.out.println("响应状态码- " + ret);
            }
        } catch (ClientProtocolException e) {
            System.out.println("Post ClientProtocolException"+ e);
        } catch (IOException e) {
            System.out.println("Post IOException"+e);
        } finally {
            // 释放连接
            post.releaseConnection();
        }
        return resultString;
    }
    /**
     * 发送post请求
     * @param url
     * @param body
     * @return
     */
    private static String postSendHttpAndHeader(String url, String body) {
        if(logflag)System.out.println("请求[参数] - " + body);
        long start = System.currentTimeMillis();
        if (url == null || "".equals(url)) {
            System.out.println("request url is empty.");
            return null;
        }
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.setHeader("Accept", "*/*");
        post.setHeader("Accept-Encoding", "gzip, deflate");
        post.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        post.setHeader("Cookie", "_gsid_=\"HdPZVfn6pgNVglWKnY5ZtnqtoqjFa6m7KSrPMBv/u/iTq292NwbvCkjq6sIHMexiFhRfssTFtvw=\"; ___lt_=SoZU5mOzhqZfCKNp5L0lwvOH4ju62hjSWpnDIf7t/Pyb0tTa0nUI6Vzog+hnbURO; ___lk__=SDQl3GEFCLUnmmCG167WNDMvq6XmWA0Z8yh7XG9tpyG8f+KhTxnY3w==; _grms_sid_=1533609118057018726500251; _gi___=\"6NW4gXKC5ruU935CGzNim4lynOQIk24hPd2yitsxmH4=\"; __u__t__=\"dqUrwJS4bMjsj/z204BEv52lcrHYwhMgDAJuhnKouqIFFSeDa75zjQ==\"; _u__a_=\"gESTklO0QxHiq2BWX9/EpFZ+DUrVuqg0PPVDK63dCh3bvY6u3vhk6mViVRomcbOOpioQ4L3rNwwbpv9u6A1UAHa9yRzNWLDWE1+hq5aH2Ojyud75rLfKq9q/5C+Y0R0j+MSH2YcMJmhh4YVcBjR22spEIOQllJ9BBxY6uFQH2lHMT2wIRqqBVhm5s6yEDfDEaLoQCItnddRz49l32GtAmLDoTXbRVDGFhFLKSII/xKl8wwSzVlxr2WPr9v0QNwbA8jxtbVoUzc+eol77h3GEvDfLnBf+qJrci5toEBuMNsWQEwYvpag6ymNnISfGa+5+vXXLXK3OgIPz+GMl6jq7BXYIICyoTGmMVYT6fbuk6xU5l6K0T/p/mlZCsfOY7f1XhCZEf4jq0kq8pzpT/+DpQZM2xo/sREbVZEhG4jL7rb1j29ETVeDONLChTE1d6Kt1xhSEN7eYnmcUqHvKya6EhR9dCVehhbY3PxMOD4ckMr6Lc1cGf2zW7I+eRsAp1208lkfvniUox8MtM0wWMFYFyVskj6gTJu2oVKdRPd6MmBjK016bYOJGdCL9MzeCON3AuEaV+1P/ZY0XMO12APRY+IE27JDyaHO+hpDpeggmA7ej5PjbylRVKMznxZMfxV/vUgGLC2fwQ4zwPFVtYeD+IfW/+vfomsjE\"; _gp___=\"Jb3lO+73xFX+IM3UHoiLl9W/wZrVKZ4F1Ig3brr0uUsVcOJDNTDoXg==\"; _guli___=\"NbflyAQdq5m2kLmHrbHwMEyrOvYXgnltL0o52rtwjUPE/dbPzxj/h4BGJP7tXx6UgBAN1iZbvRM=\"; ___lt_=\"91WKgjlgckHbBmKLeZ9H5I9hXlX+eETnfm2nA6gX5993A6XsDhuLOyuAOb8pwz/d\"; ___lk__=\"ijydFXn6pDZVFYV4AGXCRyE8hAb5xvSVtlIYEFuWZ+qNLy3cWbTpTw==\"");
        post.setHeader("DNT", "1");
        post.setHeader("Host", "hati.gops.guahao.cn");
        post.setHeader("Origin", "http://hati.gops.guahao.cn");
        post.setHeader("Referer", "http://hati.gops.guahao.cn");
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0");
        post.setHeader("X-Requested-With", "XMLHttpRequest");
//         Accept:*/*
//        Accept-Encoding:gzip, deflate
//        Accept-Language:
//        Connection:keep-alive
//        Content-Length:137
//        Content-Type:application/x-www-form-urlencoded; charset=UTF-8
//        Cookie:_gsid_="HdPZVfn6pgNVglWKnY5ZtnqtoqjFa6m7KSrPMBv/u/iTq292NwbvCkjq6sIHMexiFhRfssTFtvw="; ___lt_=SoZU5mOzhqZfCKNp5L0lwvOH4ju62hjSWpnDIf7t/Pyb0tTa0nUI6Vzog+hnbURO; ___lk__=SDQ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wcVKnnSTiIOZIz6cikOh8w8"; ___lk__="KL3DVfIa6jow7040IPQWsE3M8a2kkl5c4H/2/cdUFUBli8pkcdrDQQ=="
//        DNT:1
//        Host:hati.gops.guahao.cn
//        Origin:
//        Referer:http://hati.gops.guahao.cn/dataquery/queryview
//        User-Agent:
//        X-Requested-With:

        String resultString = null;
        try {
            StringEntity stringEntity = new StringEntity(body, "UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
            // 设置请求主体
            post.setEntity(stringEntity);
            // 发起交易
            HttpResponse resp = httpClient.execute(post);
            int ret = resp.getStatusLine().getStatusCode();
            if (ret == HttpStatus.SC_OK) {
                // 响应分析
                HttpEntity entity = resp.getEntity();

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuffer responseString = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                    responseString.append(result);
                    result = br.readLine();
                }
                long end = System.currentTimeMillis();
                if(logflag)  System.out.println("请求[" + url + "]消耗时间 " + (end - start) + "毫秒");
                resultString = responseString.toString();
                if(logflag) System.out.println("响应内容 - " + resultString);
            } else {
                if(logflag)System.out.println("响应状态码- " + ret);
            }
        } catch (ClientProtocolException e) {
            System.out.println("Post ClientProtocolException"+ e);
        } catch (IOException e) {
            System.out.println("Post IOException"+e);
        } finally {
            // 释放连接
            post.releaseConnection();
        }
        return resultString;
    }

    /**
     * get请求
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, String param) {
        if (url == null || "".equals(url)) {
            if(logflag)System.out.println("request url is empty.");
            return null;
        }
        String rquestUrl = url;
        try {
            if (StringUtils.isNotBlank(param)) {
                if (url.indexOf("?") != -1) {
                    rquestUrl += "&" + param;
                } else {

                    rquestUrl += "?" + param;
                }
            }
            return sendGetHttp(rquestUrl);
        } catch (Exception e) {
            System.out.println("send post with https error -> " + e);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 发送get请求
     * @param url
     * @return
     */
    private static String sendGetHttp(String url) {
        long start = System.currentTimeMillis();
        HttpGet get = new HttpGet(url);
        get.setConfig(requestConfig);
        String resultString = null;
        try {
            // 用get方法发送http请求
            if(logflag)System.out.println("执行get请求:...." + url);
            HttpResponse resp = httpClient.execute(get);
            int ret = resp.getStatusLine().getStatusCode();
            if (ret == HttpStatus.SC_OK) {
                // 响应分析
                HttpEntity entity = resp.getEntity();

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuffer responseString = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                    responseString.append(result);
                    result = br.readLine();
                }
                long end = System.currentTimeMillis();
                if(logflag)System.out.println("请求[" + url + "]消耗时间 " + (end - start) + "毫秒");
                resultString = responseString.toString();
                if(logflag)System.out.println("响应内容 - " + resultString);
            } else {
                if(logflag)System.out.println("响应状态码- " + ret);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            get.releaseConnection();
        }
        return resultString;
    }
public static JSONObject getJsonResult(String sql){
    String result=getResult(sql);
    return JSONObject.parseObject(result);
}
public static JSONArray getJsonArrayDatasResult(String sql){
    String result=getResult(sql);
    JSONObject jsonObject = JSONObject.parseObject(result);
    JSONArray datas=jsonObject.getJSONObject("data").getJSONObject("data").getJSONArray("data");
    return datas;
}
public static String getResult(String sql){

    return getResult(sql,"medicine","100");
}
public static String getResult(String sql,String db,String num){
    String url="http://hati.gops.guahao.cn/dataquery/query";
    String ext="sql="+sql+"&dbName="+db+"&limit="+num;
    String str=HttpUtils.post3(url,ext);
    return str;
}
    public static void main(String[] args) {
        //        String url="http://test.rqbao.com:8080/payment/trade/batchTransfer";
        //        String ext="subOrderList=%5B%7B%22amount%22%3A%22370%22%2C%22bizType%22%3A%228001%22%2C%22ftype%22%3A%2205%22%2C%22payUserId%22%3A%22%22%2C%22receiveUserId%22%3A%2236424a3505844be78c0583615bc46e18%22%2C%22remark%22%3A%22%BB%D8%BF%EE%C0%FB%CF%A2%5B%B4%E6%B9%DC%B2%E2%CA%D490%CC%EC%B1%EA%C4%A3%B0%E5_GQY8%5D-%BC%D3%CF%A2%C8%AF%CA%B9%D3%C3%B3%C9%B9%A6%22%2C%22subOrderId%22%3A%22a36546bfeeab44fda926e804379caf9c%22%7D%5D";
        //        HttpUtils.post2(url,ext);
//        String url="http://localhost:8011/360/api/userImage360";
//        String ext="name=赵邓毫&idNumber=410526199506213774&userId=d20597f4868a43a9b2b2a1bf73c6e8d2&phone=17610381617";
//        HttpUtils.post2(url,ext);
//        String url="http://hati.gops.guahao.cn/dataquery/query";
//        String ext="sql=select * from medicine_enterprise_relation where medicine_id='b49f372f-58b1-4a9a-9f4b-6399bdb2804b'&dbName=medicine&limit=100";
//        String str=HttpUtils.post3(url,ext);
        JSONArray datas=getJsonArrayDatasResult("select * from medicine_enterprise_relation where medicine_id='b49f372f-58b1-4a9a-9f4b-6399bdb2804b'");
        System.out.println(datas.getJSONArray(1).get(0));
    }
}